package cn.sofwin.sb.core.mvc.service.impl;

import cn.sofwin.sb.core.mvc.dao.BaseDao;
import cn.sofwin.sb.core.mvc.entity.IdEntity;
import cn.sofwin.sb.core.mvc.service.BaseService;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 基础服务接口的抽象实现类
 *
 * @param <T>
 */
public abstract class BaseServiceImpl<T extends IdEntity> implements BaseService<T> {

    private BaseDao baseDao;

    /**
     * 在抽象的父类中，动态获取子类注入的DAO对象
     * @return
     */
    protected BaseDao getDao() {
        if(baseDao == null) {
            Field[] fields = this.getClass().getDeclaredFields();
            try {
                cn.sofwin.sb.core.annotation.BaseDao bd = null;
                for (Field field : fields){
                    bd = field.getDeclaredAnnotation(cn.sofwin.sb.core.annotation.BaseDao.class);
                    if(bd != null){
                        field.setAccessible(true);
                        baseDao = (BaseDao) field.get(this);
                        break;
                    }
                }

                if(baseDao == null){
                    throw new RuntimeException("没有找到合适的DAO，请检查代码....");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return baseDao;
    }

    @Override
    public T creat(T entity) {
        return null;
    }

    public T create(T entity) {
        getDao().insert(entity);
        return entity;
    }

    @Override
    public void remove(Integer id) {
        getDao().delete(id);
    }

    @Override
    public T save(T entity) {
        getDao().update(entity);
        return entity;
    }

    @Override
    public T get(Integer id) {
        return (T) getDao().selectById(id);
    }

    @Override
    public List list(String query, String sort, Integer pageNo, Integer pageSize) {
        // TODO 这个大坑留给大家去填吧
        return null;
    }
}

